package com.yeyks.common.utils;

/**
 * @program: admin_server
 * @description:
 * @author: chenzheng
 * @create: 2019-04-08 16:17
 **/
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Map;

//@Component
public class ApplicationContextUtil {

    @Autowired
    private ApplicationContext applicationContext;

    private ArrayList<String> allUrlList;

    @PostConstruct
    public void init() {
        getAllUrl();
    }

    public ArrayList<String> getAllUrl() {
        if (allUrlList == null || allUrlList.size() < 1) {
            refresh();
        }
        return allUrlList;
    }

    private void refresh() {
        synchronized (ApplicationContextUtil.class) {
            ArrayList<String> allUrlListTemp = new ArrayList<>();
            Map<String, RequestMappingHandlerMapping> stringRequestMappingHandlerMappingMap = applicationContext.getBeansOfType(RequestMappingHandlerMapping.class);
            //请求url和处理方法的映射
            for (RequestMappingHandlerMapping requestMappingHandlerMapping : stringRequestMappingHandlerMappingMap.values()) {
                Map<RequestMappingInfo, HandlerMethod> handlerMethods = requestMappingHandlerMapping.getHandlerMethods();
                for (Map.Entry<RequestMappingInfo, HandlerMethod> requestMappingInfoHandlerMethodEntry : handlerMethods.entrySet()) {
                    RequestMappingInfo requestMappingInfo = requestMappingInfoHandlerMethodEntry.getKey();
                    HandlerMethod mappingInfoValue = requestMappingInfoHandlerMethodEntry.getValue();
                    RequestMethodsRequestCondition methodCondition = requestMappingInfo.getMethodsCondition();
                    PatternsRequestCondition patternsCondition = requestMappingInfo.getPatternsCondition();
                    String requestUrl = patternsCondition.getPatterns().iterator().next();
                    allUrlListTemp.add(requestUrl);
                }
            }
            allUrlList = allUrlListTemp;
        }
    }

}
